<template>
  <div class="agent-chat-container">
    <!-- 左侧智能体列表 -->
    <div class="agent-sidebar">
      <div class="sidebar-header">
        <h3>智能体列表</h3>
        <div class="header-actions">
          <el-button type="primary" icon="Refresh" circle size="small" @click="refreshAgentList" :loading="loading" />
          <el-button v-if="isDev" type="success" icon="Plus" circle size="small" @click="addTestAgent" title="添加测试智能体" />
          <el-button type="primary" size="small" @click="goToAgentManage">
            管理智能体
          </el-button>
        </div>
      </div>

      <div class="agent-list">
        <el-skeleton v-if="loading" :rows="5" animated />
        <template v-else>
          <div
            v-for="agent in agentList"
            :key="agent.id"
            :class="['agent-item', currentAgent?.id === agent.id ? 'active' : '']"
            @click="selectAgent(agent)"
          >
            <el-avatar :size="40" :src="agent.avatar">
              {{ agent.name.charAt(0) }}
            </el-avatar>
            <div class="agent-item-info">
              <div class="agent-name">{{ agent.name }}</div>
              <div class="agent-desc">{{ agent.description || '暂无描述' }}</div>
            </div>
          </div>
          <div v-if="agentList.length === 0" class="empty-agents">
            <el-empty description="暂无智能体" />
          </div>
          <div v-else-if="agentList.length < pagination.total" class="load-more">
            <el-button
              type="primary"
              link
              :loading="loadingMore"
              @click="loadMoreAgents"
            >
              加载更多
            </el-button>
          </div>
        </template>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <template v-if="currentAgent">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="agent-info">
            <el-avatar :size="40" :src="currentAgent.avatar">
              {{ currentAgent.name.charAt(0) }}
            </el-avatar>
            <div>
              <h3>{{ currentAgent.name }}</h3>
              <div class="connection-status" :class="{ connected: wsConnected }">
                <el-icon class="status-icon"><Connection /></el-icon>
                {{ wsConnected ? 'AI 服务已连接' : '正在连接 AI 服务...' }}
              </div>
            </div>
          </div>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="clearMessages">清空对话</el-button>
            <el-button
              v-if="!wsConnected"
              type="warning"
              size="small"
              @click="initWebSocket"
              :loading="connecting"
            >
              重新连接
            </el-button>
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <div v-for="(message, index) in messages" :key="index"
               :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
            <div class="message-avatar">
              <el-avatar :size="40" :src="message.role === 'user' ? userAvatar : currentAgent.avatar">
                {{ message.role === 'user' ? '我' : currentAgent.name.charAt(0) }}
              </el-avatar>
            </div>
            <div class="message-content">
              <div v-if="message.role === 'user'" class="user-content">
                {{ message.content }}
              </div>
              <div v-else-if="message.role === 'reasoning'" class="reasoning-content markdown-body" v-html="renderMarkdown(message.content)">
              </div>
              <div v-else class="ai-content markdown-body" v-html="renderMarkdown(message.content)"></div>
            </div>
          </div>
          <div v-if="isThinking" class="message ai-message">
            <div class="message-avatar">
              <el-avatar :size="40" :src="currentAgent.avatar">
                {{ currentAgent.name.charAt(0) }}
              </el-avatar>
            </div>
            <div class="message-content thinking-content">
              <el-icon class="thinking-icon"><Loading /></el-icon>
              正在思考...
            </div>
          </div>
          <div v-if="messages.length === 0 && !isThinking" class="empty-messages">
            <el-empty description="暂无对话，开始和智能体聊天吧" />
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题..."
            :disabled="!wsConnected || isThinking"
            @keyup.enter.ctrl="handleSend"
          />
          <div class="input-actions">
            <span class="hint">Ctrl + Enter 发送</span>
            <el-button
              type="primary"
              @click="handleSend"
              :loading="isThinking"
              :disabled="!wsConnected || !userInput.trim()"
            >
              发送
            </el-button>
          </div>
        </div>
      </template>

      <el-empty v-else description="请选择一个智能体开始对话" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading, Connection, Refresh, Plus } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import http from "@/utils/request.js"
import config from "@/config"

// 路由
const router = useRouter()

// 状态
const loading = ref(false)
const agentList = ref([])
const currentAgent = ref(null)
const userInput = ref('')
const messages = ref([])
const isThinking = ref(false)
const wsConnected = ref(false)
const connecting = ref(false)
const messagesContainer = ref(null)
const userAvatar = ref('')
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
})
const loadingMore = ref(false)

// WebSocket 相关
let ws = null
let reconnectAttempts = 0
const MAX_RECONNECT_ATTEMPTS = 3

// Markdown 渲染器
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true
})

// 渲染 Markdown
const renderMarkdown = (content) => {
  if (!content) return ''
  return md.render(content)
}

// 是否为开发环境
const isDev = import.meta.env.DEV || import.meta.env.MODE === 'development'

// 初始化
onMounted(() => {
  fetchAgentList()
  initUserAvatar()
})

// 组件销毁时关闭 WebSocket
onUnmounted(() => {
  closeWebSocket()
})

// 获取智能体列表
const fetchAgentList = async (isLoadMore = false) => {
  if (isLoadMore) {
    loadingMore.value = true
  } else {
    loading.value = true
    // 重置页码
    pagination.value.page = 1
  }

  try {
    const res = await http.post('/agent/search', {
      no: pagination.value.page,
      size: pagination.value.size
    })

    if (res.code === 200) {
      // 检查返回数据结构
      console.log('智能体列表数据:', res.data)

      let content = []
      let total = 0

      // 处理不同的数据结构
      if (res.data && Array.isArray(res.data)) {
        // 直接是数组的情况
        content = res.data
        total = res.total || res.data.length
      } else if (res.data && res.data.content && Array.isArray(res.data.content)) {
        // 标准分页结构
        content = res.data.content
        total = res.data.totalElements || res.data.total || content.length
      } else if (res.data && res.data.records && Array.isArray(res.data.records)) {
        // MyBatis Plus 分页结构
        content = res.data.records
        total = res.data.total || content.length
      } else if (res.data && typeof res.data === 'object') {
        // 其他可能的结构，尝试提取数据
        content = res.data.list || res.data.items || res.data.data || []
        total = res.data.total || res.data.count || content.length
      }

      if (isLoadMore) {
        // 加载更多时，追加数据
        agentList.value = [...agentList.value, ...content]
      } else {
        // 首次加载或刷新时，替换数据
        agentList.value = content
      }

      // 更新分页信息
      pagination.value.total = total

      // 如果没有数据，显示提示
      if (agentList.value.length === 0) {
        console.log('没有找到智能体数据')

        // 开发环境下，添加测试数据
        if (isDev) {
          console.log('添加测试数据')
          agentList.value = [
            {
              id: 1,
              name: '通用助手',
              description: '可以回答各种问题的智能助手',
              avatar: ''
            },
            {
              id: 2,
              name: '代码专家',
              description: '专注于编程和技术问题',
              avatar: ''
            },
            {
              id: 3,
              name: '数据分析师',
              description: '帮助分析和理解数据',
              avatar: ''
            }
          ]
          pagination.value.total = agentList.value.length
        }
      }
    } else {
      ElMessage.error(res.msg || '获取智能体列表失败')

      // 开发环境下，添加测试数据
      if (isDev) {
        console.log('添加测试数据')
        agentList.value = [
          {
            id: 1,
            name: '通用助手',
            description: '可以回答各种问题的智能助手',
            avatar: ''
          },
          {
            id: 2,
            name: '代码专家',
            description: '专注于编程和技术问题',
            avatar: ''
          },
          {
            id: 3,
            name: '数据分析师',
            description: '帮助分析和理解数据',
            avatar: ''
          }
        ]
        pagination.value.total = agentList.value.length
      }
    }
  } catch (error) {
    console.error('获取智能体列表失败:', error)
    ElMessage.error('获取智能体列表失败')

    // 开发环境下，添加测试数据
    if (isDev) {
      console.log('添加测试数据')
      agentList.value = [
        {
          id: 1,
          name: '通用助手',
          description: '可以回答各种问题的智能助手',
          avatar: ''
        },
        {
          id: 2,
          name: '代码专家',
          description: '专注于编程和技术问题',
          avatar: ''
        },
        {
          id: 3,
          name: '数据分析师',
          description: '帮助分析和理解数据',
          avatar: ''
        }
      ]
      pagination.value.total = agentList.value.length
    }
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 初始化用户头像
const initUserAvatar = () => {
  // 这里可以从用户信息中获取头像，或者使用默认头像
  userAvatar.value = ''
}

// 选择智能体
const selectAgent = (agent) => {
  currentAgent.value = agent
  messages.value = []
  closeWebSocket()
  initWebSocket()
}

// 初始化 WebSocket 连接
const initWebSocket = () => {
  if (!currentAgent.value) return

  connecting.value = true
  wsConnected.value = false

  // 关闭现有连接
  closeWebSocket()

  // 创建新连接
  const wsUrl = `${config.WS_URL}/websocket?agentId=${currentAgent.value.id}`
  ws = new WebSocket(wsUrl)

  ws.onopen = () => {
    wsConnected.value = true
    connecting.value = false
    reconnectAttempts = 0
    ElMessage.success('AI 服务连接成功')
  }

  ws.onmessage = (event) => {
    handleWebSocketMessage(event.data)
  }

  ws.onerror = (error) => {
    console.error('WebSocket 错误:', error)
    wsConnected.value = false
    connecting.value = false
    ElMessage.error('AI 服务连接失败')
  }

  ws.onclose = () => {
    wsConnected.value = false
    connecting.value = false

    // 尝试重连
    if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
      reconnectAttempts++
      setTimeout(() => {
        if (!wsConnected.value) {
          initWebSocket()
        }
      }, 3000)
    }
  }
}

// 处理 WebSocket 消息
const handleWebSocketMessage = (data) => {
  try {
    const response = JSON.parse(data)

    if (response.messageType === 'reasoning') {
      // 思考中
      isThinking.value = true
      // 检查是否已有推理消息，如果有则累加内容，否则创建新消息
      if (messages.value.length > 0 && messages.value[messages.value.length - 1].role === 'reasoning') {
        // 更新现有的推理消息
        messages.value[messages.value.length - 1].content += response.content
      } else {
        // 添加新的推理消息
        messages.value.push({
          role: 'reasoning',
          content: response.content
        })
      }
      scrollToBottom()
    } else if (response.messageType === 'content') {
      // 正常消息
      // 检查是否已有助手消息，如果有则累加内容，否则创建新消息
      if (messages.value.length > 0 &&
          messages.value[messages.value.length - 1].role === 'assistant') {
        // 更新现有的助手消息
        messages.value[messages.value.length - 1].content += response.content
      } else {
        // 添加新的助手消息
        messages.value.push({
          role: 'assistant',
          content: response.content
        })
      }
      scrollToBottom()
    } else if (response.messageType === 'over') {
      // 错误消息
      isThinking.value = false
    }
  } catch (error) {
    console.error('处理 WebSocket 消息失败:', error)
  }
}

// 关闭 WebSocket 连接
const closeWebSocket = () => {
  if (ws) {
    ws.close()
    ws = null
  }
}

// 发送消息
const handleSend = () => {
  if (!wsConnected.value || isThinking.value || !userInput.value.trim()) {
    return
  }

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: userInput.value
  })

  // 发送消息到服务器
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'prompt',
      message: userInput.value,
      options: {
        showReasoning: true, // 始终显示推理过程
        streamResponse: true // 启用流式响应
      }
    }))

    // 清空输入框
    userInput.value = ''

    // 显示思考状态
    isThinking.value = true

    // 滚动到底部
    scrollToBottom()
  } else {
    ElMessage.error('AI 服务未连接，请重试')
  }
}

// 清空消息
const clearMessages = () => {
  messages.value = []
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 跳转到智能体管理页面
const goToAgentManage = () => {
  router.push('/chat/agent')
}

// 添加加载更多智能体的函数
const loadMoreAgents = () => {
  if (loadingMore.value) return
  if (agentList.value.length >= pagination.value.total) return

  pagination.value.page++
  fetchAgentList(true)
}

// 添加刷新智能体列表的函数
const refreshAgentList = () => {
  fetchAgentList()
}

// 添加测试智能体的函数
const addTestAgent = () => {
  const id = Date.now()
  const newAgent = {
    id,
    name: `测试智能体 ${agentList.value.length + 1}`,
    description: '这是一个测试智能体',
    avatar: ''
  }

  agentList.value.push(newAgent)
  pagination.value.total = agentList.value.length

  ElMessage.success('已添加测试智能体')
}
</script>

<style scoped>
.agent-chat-container {
  display: flex;
  height: 100%;
  overflow: hidden;
}

.agent-sidebar {
  width: 280px;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
}

.sidebar-header .header-actions {
  display: flex;
  gap: 8px;
}

.agent-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.empty-agents {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.load-more {
  text-align: center;
  padding: 10px 0;
  margin-top: 10px;
  border-top: 1px dashed #e0e0e0;
}

.agent-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 6px;
  cursor: pointer;
  margin-bottom: 8px;
  transition: background-color 0.3s;
}

.agent-item:hover {
  background-color: #ecf5ff;
}

.agent-item.active {
  background-color: #ecf5ff;
  border-left: 3px solid #409eff;
}

.agent-item-info {
  margin-left: 10px;
  flex: 1;
  overflow: hidden;
}

.agent-name {
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.agent-desc {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.agent-info {
  display: flex;
  align-items: center;
}

.agent-info h3 {
  margin: 0 0 5px 10px;
  font-size: 16px;
}

.connection-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #f56c6c;
  margin-left: 10px;
}

.connection-status.connected {
  color: #67c23a;
}

.status-icon {
  margin-right: 5px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f7fa;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.message-avatar {
  margin-right: 10px;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  border-radius: 8px;
  padding: 12px;
  position: relative;
}

.user-message .message-content {
  margin-left: auto;
  background-color: #ecf5ff;
}

.ai-message .message-content {
  background-color: #fff;
}

.user-content {
  white-space: pre-wrap;
  word-break: break-word;
}

.ai-content {
  white-space: pre-wrap;
  word-break: break-word;
}

.reasoning-content {
  background-color: #f8f8f8;
  border: 1px dashed #dcdfe6;
  padding: 10px;
  font-style: italic;
  color: #606266;
  font-size: 13px;
  position: relative;
  margin-top: 5px;
  border-radius: 6px;
}

.reasoning-content::before {
  content: "推理过程";
  position: absolute;
  top: -10px;
  left: 10px;
  background-color: #f8f8f8;
  padding: 0 5px;
  font-size: 12px;
  color: #909399;
  border: 1px dashed #dcdfe6;
  border-radius: 3px;
}

.thinking-content {
  display: flex;
  align-items: center;
}

.thinking-icon {
  animation: rotating 2s linear infinite;
  margin-right: 8px;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.empty-messages {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  background-color: #fff;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.hint {
  font-size: 12px;
  color: #909399;
}

/* Markdown 样式 */
.markdown-body {
  font-size: 14px;
  line-height: 1.6;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 16px;
  margin-bottom: 16px;
  font-weight: 600;
}

.markdown-body code {
  background-color: #f5f7fa;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.markdown-body pre {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
}

.markdown-body pre code {
  background-color: transparent;
  padding: 0;
}

.markdown-body table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

.markdown-body table th,
.markdown-body table td {
  border: 1px solid #dcdfe6;
  padding: 8px;
}

.markdown-body table th {
  background-color: #f5f7fa;
}

.markdown-body blockquote {
  border-left: 4px solid #dcdfe6;
  padding-left: 16px;
  margin-left: 0;
  color: #606266;
}

.markdown-body img {
  max-width: 100%;
}

.markdown-body a {
  color: #409eff;
  text-decoration: none;
}

.markdown-body a:hover {
  text-decoration: underline;
}
</style>
